﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Card.Common;
using System.Text;

namespace Card.Web
{
    public partial class Design : BasePage
    {
        #region
        private int m_CardId = 0;
        /// <summary>
        /// 名片ID
        /// </summary>
        private int CardID
        {
            get
            {
                if (m_CardId <= 0)
                {
                    if (Request.QueryString["id"] != null && int.TryParse(Request.QueryString["id"], out m_CardId))
                    {
                        return m_CardId;
                    }

                }
                return m_CardId;
            }
        }

        /// <summary>
        /// 是否User Card
        /// </summary>
        public bool IsUserCard
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["u"]) && BAF.Utility.ValidationHelper.IsNumber(Request.QueryString["u"]))
                {
                    return this.Passport.UserID == int.Parse(Request.QueryString["u"]);
                }
                return false;
            }
        }

        private Card.Entity.Template m_Template = null;

        public Card.Entity.Template Template
        {
            get { return m_Template; }
            set { m_Template = value; }
        }

        
        #endregion

        #region
        protected void Page_Load(object sender, EventArgs e)
        {
            this.DoInit();
        }
        #endregion

        #region
        private void DoInit()
        {
            if (this.IsUserCard)
            {
                this.DoInitUserCard();
            }
            else
            {
                this.DoInitSysTemplate();
            }
        }

        private void DoInitSysTemplate()
        {
            m_Template = BLL.TemplateManager.GetEntityByStatus(this.CardID, CONST.TEMPLATE_STATUS.ACTIVE, null);
            
            if (m_Template == null)
            {
                m_Template = BLL.TemplateManager.RandomTemplate();
                this.m_CardId = m_Template.ID;
            }

            if (string.Compare(m_Template.Style, CONST.TEMPLATE_STYLE.VERTICAL, true) == 0)
            {
                this.card_ctn.Attributes.Add("class", "vertical");
            }
            else
            {
                this.card_ctn.Attributes.Add("class", "horizontal");
            }

            this.FaceImg.ImageUrl = Utility.ImageUtilty.GetTemplateThumbImagePath(m_Template.FrontImage);
            this.BackImg.ImageUrl = Utility.ImageUtilty.GetTemplateThumbImagePath(m_Template.BackImage);
            this.ltlCardName.Text = m_Template.Name;
            this.hndInfo.Value = Security.Utility.EncryptString(string.Format("{0}|{1}|{2}|{3}|{4}", m_Template.FrontImage, m_Template.BackImage, m_Template.ID, m_Template.Name, m_Template.Style));

            DataSet dsList = BLL.TemplateFieldManager.GetList(string.Format(" TEMPLATE_ID={0} ORDER BY SORT,ID", this.CardID), null);

            StringBuilder sbFrontImages = new StringBuilder();
            StringBuilder sbBackImages = new StringBuilder();
            StringBuilder sbFrontField = new StringBuilder();
            StringBuilder sbBackField = new StringBuilder();

            DataRow[] frontRows = dsList.Tables[0].Select(string.Format("IMAGE_TYPE='{0}'", CONST.CARD_FACE_TYPE.FRONT));

            foreach (DataRow dr in frontRows)
            {
                sbFrontImages.Append(CardWebUtility.CreateFieldImageHTML(dr["SORT"].ToString(), CONST.CARD_FACE_TYPE.FRONT));
                sbFrontField.Append(CardWebUtility.CreateFieldHTML(CONST.CARD_FACE_TYPE.FRONT,
                      dr["SORT"].ToString(),
                      dr["CONTENT"].ToString(),
                      dr["POS_X"].ToString(),
                      dr["POS_Y"].ToString(),
                      dr["DIRECTION"].ToString(),
                      dr["COLOR"].ToString(),
                      dr["FONT_FAMILY"].ToString(),
                      dr["FONT_SIZE"].ToString(),
                      dr["FONT_STYLE"].ToString()));
            }

            DataRow[] backRows = dsList.Tables[0].Select(string.Format("IMAGE_TYPE='{0}'", CONST.CARD_FACE_TYPE.BACK));
            foreach (DataRow dr in backRows)
            {
                sbBackImages.Append(CardWebUtility.CreateFieldImageHTML(dr["SORT"].ToString(), CONST.CARD_FACE_TYPE.BACK));
                sbBackField.Append(CardWebUtility.CreateFieldHTML(CONST.CARD_FACE_TYPE.BACK,
                      dr["SORT"].ToString(),
                      dr["CONTENT"].ToString(),
                      dr["POS_X"].ToString(),
                      dr["POS_Y"].ToString(),
                      dr["DIRECTION"].ToString(),
                      dr["COLOR"].ToString(),
                      dr["FONT_FAMILY"].ToString(),
                      dr["FONT_SIZE"].ToString(),
                      dr["FONT_STYLE"].ToString()));
            }

            Entity.TemplateLogo tempLogo = new Card.Entity.TemplateLogo()
            {
                Height = 0,
                Width = 0,
                ImageType = CONST.CARD_FACE_TYPE.FRONT,
                Logo = "transparent.gif",
                PosX = 0,
                PosY = 0
            };

            Entity.TemplateLogo logoF = BLL.TemplateLogoManager.GetEntity(this.CardID, CONST.CARD_FACE_TYPE.FRONT, this.Passport);
            if (logoF != null)
            {
                sbFrontImages.Append(CardWebUtility.CreateLogoHTML(logoF));
                this.frontLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(logoF.Logo);
            }
            else
            {
                sbFrontImages.Append(CardWebUtility.CreateLogoHTML(tempLogo));
                this.frontLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(tempLogo.Logo);
            }

            Entity.TemplateLogo logoB = BLL.TemplateLogoManager.GetEntity(this.CardID, CONST.CARD_FACE_TYPE.BACK, this.Passport);
            if (logoB != null)
            {
                sbBackImages.Append(CardWebUtility.CreateLogoHTML(logoB));
                this.backLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(logoB.Logo);
            }
            else
            {
                tempLogo.ImageType = CONST.CARD_FACE_TYPE.BACK;
                sbBackImages.Append(CardWebUtility.CreateLogoHTML(tempLogo));
                this.backLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(tempLogo.Logo);
            }

            this.ltlBackImages.Text = sbBackImages.ToString();
            this.ltlFrontImages.Text = sbFrontImages.ToString();

            this.ltlFrontFields.Text = sbFrontField.ToString();
            this.ltlBackFields.Text = sbBackField.ToString();

            this.BindNextPrev();
        }

        private void DoInitUserCard()
        {
            Card.Entity.UserCard card = BLL.UserCardManager.GetEntity(this.CardID, null);

            if (card == null || card.UserID != this.Passport.UserID)
            {
                Response.Redirect("Default.aspx");
                return;
            }

            if (string.Compare(card.Style, CONST.TEMPLATE_STYLE.VERTICAL, true) == 0)
            {
                this.card_ctn.Attributes.Add("class", "vertical");
            }
            else
            {
                this.card_ctn.Attributes.Add("class", "horizontal");
            }

            this.FaceImg.ImageUrl = Utility.ImageUtilty.GetTemplateThumbImagePath(card.FrontImage);
            this.BackImg.ImageUrl = Utility.ImageUtilty.GetTemplateThumbImagePath(card.BackImage);
            this.ltlCardName.Text = card.TemplateName;
            this.hndInfo.Value = Security.Utility.EncryptString(string.Format("{0}|{1}|{2}|{3}|{4}", card.FrontImage, card.BackImage, card.TemplateID, card.TemplateName, card.Style));
            this.hndUserCardID.Value = card.ID.ToString();

            DataTable dtFields = BLL.UserCardFieldManager.GetList(string.Format(" USER_CARD_ID={0} ORDER BY SORT,ID", this.CardID), null).Tables[0];

            StringBuilder sbFrontImages = new StringBuilder();
            StringBuilder sbBackImages = new StringBuilder();
            StringBuilder sbFrontField = new StringBuilder();
            StringBuilder sbBackField = new StringBuilder();

            DataRow[] frontRows = dtFields.Select(string.Format("IMAGE_TYPE='{0}'", CONST.CARD_FACE_TYPE.FRONT));

            foreach (DataRow dr in frontRows)
            {
                sbFrontImages.Append(CardWebUtility.CreateFieldImageHTML(dr["SORT"].ToString(), CONST.CARD_FACE_TYPE.FRONT));
                sbFrontField.Append(Common.CardWebUtility.CreateFieldHTML(CONST.CARD_FACE_TYPE.FRONT,
                      dr["SORT"].ToString(),
                      dr["CONTENT"].ToString(),
                      dr["POS_X"].ToString(),
                      dr["POS_Y"].ToString(),
                      dr["DIRECTION"].ToString(),
                      dr["COLOR"].ToString(),
                      dr["FONT_FAMILY"].ToString(),
                      dr["FONT_SIZE"].ToString(),
                      dr["FONT_STYLE"].ToString()));
            }

            Entity.TemplateLogo tempLogo = new Card.Entity.TemplateLogo()
            {
                Height = 0,
                Width = 0,
                ImageType = CONST.CARD_FACE_TYPE.FRONT,
                Logo = "transparent.gif",
                PosX = 0,
                PosY = 0
            };

            Entity.UserCardLogo logoF = BLL.UserCardLogoManager.GetEntity(this.CardID, CONST.CARD_FACE_TYPE.FRONT, this.Passport);
            if (logoF != null)
            {
                sbFrontImages.Append(CardWebUtility.CreateUserCardLogoHTML(logoF));
                this.frontLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(logoF.Logo);
            }
            else
            {
                sbFrontImages.Append(CardWebUtility.CreateLogoHTML(tempLogo));
                this.frontLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(tempLogo.Logo);
            }

            DataRow[] backRows = dtFields.Select(string.Format("IMAGE_TYPE='{0}'", CONST.CARD_FACE_TYPE.BACK));
            foreach (DataRow dr in backRows)
            {
                sbBackImages.Append(CardWebUtility.CreateFieldImageHTML(dr["SORT"].ToString(), CONST.CARD_FACE_TYPE.BACK));
                sbBackField.Append(Common.CardWebUtility.CreateFieldHTML(CONST.CARD_FACE_TYPE.BACK,
                      dr["SORT"].ToString(),
                      dr["CONTENT"].ToString(),
                      dr["POS_X"].ToString(),
                      dr["POS_Y"].ToString(),
                      dr["DIRECTION"].ToString(),
                      dr["COLOR"].ToString(),
                      dr["FONT_FAMILY"].ToString(),
                      dr["FONT_SIZE"].ToString(),
                      dr["FONT_STYLE"].ToString()));
            }

            Entity.UserCardLogo logoB = BLL.UserCardLogoManager.GetEntity(this.CardID, CONST.CARD_FACE_TYPE.BACK, this.Passport);
            if (logoB != null)
            {
                sbBackImages.Append(CardWebUtility.CreateUserCardLogoHTML(logoB));
                this.backLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(logoB.Logo);
            }
            else
            {
                tempLogo.ImageType = CONST.CARD_FACE_TYPE.BACK;
                sbBackImages.Append(CardWebUtility.CreateLogoHTML(tempLogo));
                this.backLogo.ImageSrc = Card.Utility.ImageUtilty.GetLogoPath(tempLogo.Logo);
            }

            this.ltlBackImages.Text = sbBackImages.ToString();
            this.ltlFrontImages.Text = sbFrontImages.ToString();

            this.ltlFrontFields.Text = sbFrontField.ToString();
            this.ltlBackFields.Text = sbBackField.ToString();

            this.BindNextPrev();
        }

        private void BindNextPrev()
        {
            int prevID = 0;
            int nextID = 0;
            if (this.IsUserCard)
            {
                BLL.UserCardManager.GetNextPrev(this.CardID, ref prevID, ref nextID, this.Passport);
            }
            else
            {
                BLL.TemplateManager.GetTemplateNextPrev(this.CardID, ref prevID, ref nextID);
            }

            this.linkPrev.NavigateUrl = string.Format("/design.aspx?id={0}{1}", prevID, this.IsUserCard ? string.Format("&u={0}", this.Passport.UserID) : string.Empty);
            this.linkNext.NavigateUrl = string.Format("/design.aspx?id={0}{1}", nextID, this.IsUserCard ? string.Format("&u={0}", this.Passport.UserID) : string.Empty);
        }

        #endregion
    }
}
